

package cn.shengchao.examstar.me.play.acl.adapters.repositories;

import cn.shengchao.examstar.me.infrastructure.dao.ProductCourseUserDao;
import cn.shengchao.examstar.me.infrastructure.dao.ProductCourseUserPlayStatisticsDao;
import cn.shengchao.examstar.me.infrastructure.dao.po.TProductCourseUser;
import cn.shengchao.examstar.me.infrastructure.dao.po.TProductCourseUserPlayStatistics;
import cn.shengchao.examstar.me.play.acl.ports.repositories.IUserCoursePlayRepository;
import cn.shengchao.examstar.me.play.domain.Point;
import cn.shengchao.examstar.me.play.domain.UserCourse;
import cn.shengchao.examstar.me.play.domain.UserCoursePlayLog;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Slf4j
@Repository
public class UserCoursePlayRepository implements IUserCoursePlayRepository {

    @Autowired
    private ProductCourseUserPlayStatisticsDao productCourseUserPlayStatisticsDao;

    @Autowired
    private ProductCourseUserDao productCourseUserDao;

    @Override
    public void saveUserCoursePlayLog(UserCoursePlayLog userCoursePlayLog) {
        TProductCourseUserPlayStatistics statistics = new TProductCourseUserPlayStatistics();
        statistics.setActualWatchTime(userCoursePlayLog.getActualWatchTime());
        statistics.setBeginProgress(Math.toIntExact(userCoursePlayLog.getPoints().getFirst().getPoint()));
        statistics.setBeginTime(userCoursePlayLog.getPoints().getFirst().getTime());
        statistics.setCourseId(userCoursePlayLog.getCourseId());
        statistics.setEndProgress((int) userCoursePlayLog.getPoints().getLast().getPoint());
        statistics.setEndTime(userCoursePlayLog.getPoints().getLast().getTime());
        statistics.setKnowledgeNodeId(userCoursePlayLog.getKnowledgeNodeId());
        statistics.setPoints(JSON.toJSONString(userCoursePlayLog.getPoints()));
        statistics.setStudentId(userCoursePlayLog.getStudentId());
        statistics.setWatchProgress(userCoursePlayLog.getWatchProgress());
        productCourseUserPlayStatisticsDao.insert(statistics);
    }

    @Override
    public Optional<UserCourse> getUserCourse(Long userId, Long KnowledgeNodeId) {
        TProductCourseUser tProductCourseUsers = productCourseUserDao
                .selectOne(new LambdaQueryWrapper<TProductCourseUser>()
                        .eq(TProductCourseUser::getKnowledgeNodeId, KnowledgeNodeId)
                        .eq(TProductCourseUser::getDeleted, 0)
                        .eq(TProductCourseUser::getStudentId, userId));
        if (tProductCourseUsers == null) {
            return Optional.empty();
        }
        return Optional.of(of(tProductCourseUsers));
    }

    @Override
    public List<Long> getMyCoursePalyList(Long uid) {
        List<TProductCourseUserPlayStatistics> statistics = productCourseUserPlayStatisticsDao
                .selectList(new LambdaQueryWrapper<TProductCourseUserPlayStatistics>()
                        .eq(TProductCourseUserPlayStatistics::getStudentId, uid));
        return statistics.stream().map(TProductCourseUserPlayStatistics::getCourseId).toList();
    }

    @Override
    public UserCourse last(Long uid, String courseId) {
        TProductCourseUser tProductCourseUser = productCourseUserDao.lastPlay(uid, courseId);
        return of(tProductCourseUser);
    }

    private UserCourse of(TProductCourseUser tProductCourseUsers) {
        if (tProductCourseUsers == null) {
            return null;
        }
        UserCourse userCourse = new UserCourse();
        userCourse.setCourseId(tProductCourseUsers.getCourseId());
        userCourse.setKnowledgeNodeId(tProductCourseUsers.getKnowledgeNodeId());
        userCourse.setLastPlayProgress(Math.toIntExact(tProductCourseUsers.getLastPlayProgress()));
        userCourse.setLastPlayTime(tProductCourseUsers.getLastPlayTime());
        userCourse.setStudentId(tProductCourseUsers.getStudentId());
        userCourse.setUnlockTime(tProductCourseUsers.getUnlockTime());
        userCourse.setPayId(tProductCourseUsers.getPayId());
        userCourse.setWatchProgress(tProductCourseUsers.getWatchProgress());
        userCourse.setWatchLength(tProductCourseUsers.getWatchLength());
        userCourse.setProgressInfo(tProductCourseUsers.getProgressInfo());
        return userCourse;
    }

    @Override
    public void updateUserCourse(UserCourse userCourse) {
        TProductCourseUser tProductCourseUsers = productCourseUserDao
                .selectOne(new LambdaQueryWrapper<TProductCourseUser>()
                        .eq(TProductCourseUser::getKnowledgeNodeId, userCourse.getKnowledgeNodeId())
                        .eq(TProductCourseUser::getDeleted, 0)
                        .eq(TProductCourseUser::getStudentId, userCourse.getStudentId()));
        if (tProductCourseUsers == null) {
            //新增（没有买课就是试听）
            tProductCourseUsers = new TProductCourseUser();
            tProductCourseUsers.setCourseId(userCourse.getCourseId());
            tProductCourseUsers.setKnowledgeNodeId(userCourse.getKnowledgeNodeId());
            tProductCourseUsers.setLastPlayProgress(Math.toIntExact(userCourse.getLastPlayProgress()));
            tProductCourseUsers.setLastPlayTime(userCourse.getLastPlayTime());
            tProductCourseUsers.setStudentId(userCourse.getStudentId());
            tProductCourseUsers.setUnlockTime(LocalDateTime.now());
            tProductCourseUsers.setUnlockType(2L);
            tProductCourseUsers.setWatchLength(userCourse.getWatchLength());
            tProductCourseUsers.setWatchProgress(userCourse.getWatchProgress());
            tProductCourseUsers.setProgressInfo(userCourse.getProgressInfo());
            productCourseUserDao.insert(tProductCourseUsers);
        } else {
            //更新进度
            tProductCourseUsers.setLastPlayProgress(Math.toIntExact(userCourse.getLastPlayProgress()));
            tProductCourseUsers.setLastPlayTime(userCourse.getLastPlayTime());
            tProductCourseUsers.setWatchLength(userCourse.getWatchLength());
            tProductCourseUsers.setWatchProgress(userCourse.getWatchProgress());
            tProductCourseUsers.setProgressInfo(userCourse.getProgressInfo());
            productCourseUserDao.updateById(tProductCourseUsers);
        }
    }

    @Override
    public List<UserCoursePlayLog> getUserCoursePlayLog(Long userId, Date beginTime, Date endTime) {
        List<TProductCourseUserPlayStatistics> statistics = productCourseUserPlayStatisticsDao
                .selectList(new LambdaQueryWrapper<TProductCourseUserPlayStatistics>()
                        .eq(TProductCourseUserPlayStatistics::getStudentId, userId)
                        .between(TProductCourseUserPlayStatistics::getBeginTime, beginTime, endTime));
        return statistics.stream().map(item -> {
            UserCoursePlayLog userCoursePlayLog = new UserCoursePlayLog();
            userCoursePlayLog.setActualWatchTime(item.getActualWatchTime());
            userCoursePlayLog.setCourseId(item.getCourseId());
            userCoursePlayLog.setKnowledgeNodeId(item.getKnowledgeNodeId());
            userCoursePlayLog.setStudentId(item.getStudentId());
            userCoursePlayLog.setWatchProgress(item.getWatchProgress());
            try {
                userCoursePlayLog.setPoints(JSON.parseArray(item.getPoints(), Point.class));
            } catch (Exception e) {
                log.error("GZIP解析异常：{}", item.getId(), e);
            }
            userCoursePlayLog.setBeginTime(item.getBeginTime());
            return userCoursePlayLog;
        }).toList();
    }
}
